// Copyright (c) 2013-2015 David Muse
// See the COPYING file for more information.

#include <wikitext/wikitext.h>
#include <rudiments/commandline.h>
#include <rudiments/stringbuffer.h>
#include <rudiments/permissions.h>
#include <rudiments/process.h>

int main(int argc, const char **argv) {

	// get command line args...
	commandline	cmdl(argc,argv);
	const char	*inputfilename=NULL;
	if (cmdl.found("i")) {
		inputfilename=cmdl.getValue("i");
	} else {
		inputfilename=cmdl.getValue("c");
	}
	const char	*outputfilename=cmdl.getValue("o");
	uint8_t		debuglevel=charstring::toInteger(cmdl.getValue("d"));

	// validate command line args...
	if (!charstring::length(inputfilename) ||
		!charstring::length(outputfilename)) {

		stderror.printf("usage: wt -i file -o file "
				"[-xhtml [parameters]] "
				"[-plaintext] "
				"[-d debuglevel]"
				"\n");
		process::exit(1);
	}

	// read input...
	stringbuffer	input;
	if (!charstring::compare(inputfilename,"-")) {
		char	buffer[1024];
		ssize_t	sizeread=0;
		do {
			sizeread=stdinput.read(buffer,sizeof(buffer));
			if (sizeread>0) {
				input.append(buffer,sizeread);
			}
		} while (sizeread>0);
	} else {
		file	inputfile;
		if (!inputfile.open(inputfilename,O_RDONLY)) {
			stderror.printf("failed to open input file %s\n",
								inputfilename);
			process::exit(1);
		}
		input.append(inputfile.getContents(),inputfile.getSize());
		inputfile.close();
	}

	// reformat the wikitext...
	wikitext	wt;

	// set output format...
	if (cmdl.found("plaintext")) {
		wt.setOutputFormat("plaintext",NULL);
	} else {
		wt.setOutputFormat("xhtml",cmdl.getValue("xhtml"));
	}

	// set debug level
	wt.setDebugLevel(debuglevel);

	// actually do the reformatting...
	stringbuffer	output;
	if (!wt.reformat(input.getString(),&output)) {
		stderror.printf("error: %s\n",wt.getError());
		process::exit(1);
	}

	// write output...
	if (!charstring::compare(outputfilename,"-")) {

		if (stdoutput.write(output.getString())!=
					output.getStringLength()) {
			stderror.printf("failed to write to standard output\n");
			process::exit(1);
		}
				
	} else {

		file	outputfile;
		if (!outputfile.open(
			outputfilename,O_CREAT|O_WRONLY|O_TRUNC,
			permissions::evalPermString("rw-r--r--"))) {

			stderror.printf("failed to open output file %s\n",
								outputfilename);
			process::exit(1);
		}

		if (outputfile.write(output.getString())!=
					output.getStringLength()) {

			stderror.printf("failed to write to output file %s\n",
								outputfilename);
			process::exit(1);
		}
	}

	// success...
	process::exit(0);
}
